package benny_driving_ser.servlet.listener;

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;

import benny_driving_ser.util.CopiedIterator;

public class TimerListener implements ServletContextListener {

	public void contextDestroyed(ServletContextEvent arg0) {

	}

	public void contextInitialized(ServletContextEvent arg0) {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.MONTH, 11);
		c.set(Calendar.DAY_OF_MONTH, 1);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		final int MIN = 2;
		Timer timer = new Timer(true);
		TimerTask timerTask = new TimerTask() {
			Iterator<HttpSession> i = null;
			@Override
			public void run() {
				synchronized (SessionListener.SESSIONS) {
					i = new CopiedIterator(SessionListener.SESSIONS.iterator());
				}
				while (i.hasNext()) {
					i.next().invalidate();
				}
				synchronized (SessionListener.SESSIONS) {
					SessionListener.SESSIONS.clear();
				}
				Date mDate = new Date();
				mDate.setTime(System.currentTimeMillis());
				System.out.println("session clear" + mDate.toString());
			}
		};
		Date date = new Date();
		date.setTime(c.getTimeInMillis());
		timer.schedule(timerTask, date, 1000 * 60 * 60 * 24);
		System.out.println("servlet start");
	}

}
